<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-8">
    <div class="container mx-auto px-4 max-w-7xl">
      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-12">
        <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
        <p class="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
      </div>

      <!-- 工具详情 -->
      <div v-else-if="tool" class="space-y-8">
        <!-- 会员专属提示卡片 -->
        <div 
          v-if="tool.isPremium && !authStore.isPremium" 
          class="bg-gradient-to-r from-yellow-50 via-amber-50 to-orange-50 dark:from-yellow-900/20 dark:via-amber-900/20 dark:to-orange-900/20 border-2 border-yellow-400 dark:border-yellow-600 rounded-xl p-6 shadow-lg"
        >
          <div class="flex items-start gap-4">
            <div class="flex-shrink-0 w-12 h-12 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full flex items-center justify-center shadow-md">
              <Icon name="heroicons:star-solid" class="w-6 h-6 text-white" />
            </div>
            <div class="flex-1">
              <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-2 flex items-center gap-2">
                <Icon name="heroicons:lock-closed" class="w-5 h-5 text-yellow-600" />
                这是会员专属工具
              </h3>
              <p class="text-gray-700 dark:text-gray-300 mb-4">
                该工具为付费会员专享，升级会员后可以访问工具完整功能
              </p>
              <div class="flex gap-3">
                <NuxtLink 
                  to="/pricing" 
                  class="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-yellow-400 to-orange-500 text-white rounded-lg font-medium hover:from-yellow-500 hover:to-orange-600 transition-all shadow-md"
                >
                  <Icon name="heroicons:sparkles" class="w-4 h-4" />
                  立即升级会员
                </NuxtLink>
                <NuxtLink 
                  to="/pricing" 
                  class="inline-flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 border-2 border-yellow-400 dark:border-yellow-600 text-gray-900 dark:text-white rounded-lg font-medium hover:bg-yellow-50 dark:hover:bg-yellow-900/20 transition-all"
                >
                  <Icon name="heroicons:information-circle" class="w-4 h-4" />
                  了解会员权益
                </NuxtLink>
              </div>
            </div>
          </div>
        </div>

        <!-- 工具头部信息 -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-8">
          <div class="flex flex-col md:flex-row gap-8">
            <!-- Logo -->
            <div class="flex-shrink-0">
              <img
                v-if="tool.logo"
                :src="tool.logo"
                :alt="tool.name"
                class="w-24 h-24 rounded-lg object-cover"
              />
              <div
                v-else
                class="w-24 h-24 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white text-3xl font-bold"
              >
                {{ tool.name.charAt(0) }}
              </div>
            </div>

            <!-- 基本信息 -->
            <div class="flex-1">
              <div class="flex items-start justify-between mb-4">
                <div>
                  <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">
                    {{ tool.name }}
                  </h1>
                  <div class="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400">
                    <div class="flex items-center gap-1">
                      <RatingStars 
                        :model-value="Number(tool.rating)" 
                        :show-value="true"
                        :show-count="true"
                        :count="ratingStats?.totalReviews || 0"
                      />
                    </div>
                    <span>•</span>
                    <span>{{ formatNumber(tool.views) }} 浏览</span>
                    <span>•</span>
                    <span>{{ formatNumber(tool.upvotes) }} 点赞</span>
                  </div>
                </div>

                <!-- 收藏按钮 -->
                <button
                  @click="toggleFavorite"
                  class="flex items-center gap-2 px-4 py-2 rounded-lg border transition-colors"
                  :class="isFavorited 
                    ? 'bg-red-50 dark:bg-red-900/20 border-red-300 dark:border-red-700 text-red-600 dark:text-red-400'
                    : 'bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600'
                  "
                >
                  <svg class="w-5 h-5" :fill="isFavorited ? 'currentColor' : 'none'" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                  </svg>
                  {{ isFavorited ? '已收藏' : '收藏' }}
                </button>
              </div>

              <p class="text-gray-700 dark:text-gray-300 mb-4">
                {{ tool.description }}
              </p>

              <!-- 标签 -->
              <div class="flex flex-wrap gap-2 mb-6">
                <!-- 会员专属标签 -->
                <span
                  v-if="tool.isPremium"
                  class="inline-flex items-center gap-1 px-3 py-1 bg-gradient-to-r from-yellow-400 via-amber-500 to-orange-500 text-white text-sm rounded-full font-medium shadow-sm"
                >
                  <Icon name="heroicons:star-solid" class="w-3 h-3" />
                  会员专属
                </span>
                
                <span
                  v-for="tag in tool.tags"
                  :key="tag.id"
                  class="px-3 py-1 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 text-sm rounded-full"
                >
                  {{ tag.name }}
                </span>
                <span
                  v-if="tool.isFree"
                  class="px-3 py-1 bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 text-sm rounded-full"
                >
                  免费
                </span>
                <span
                  v-else-if="tool.pricing"
                  class="px-3 py-1 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 text-sm rounded-full"
                >
                  {{ tool.pricing }}
                </span>
              </div>

              <!-- 操作按钮 -->
              <div class="flex gap-3">
                <!-- 会员专属工具的访问按钮 -->
                <button
                  v-if="tool.isPremium && !authStore.isPremium"
                  @click="showUpgradePrompt"
                  class="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-yellow-400 to-orange-500 text-white rounded-lg font-medium hover:from-yellow-500 hover:to-orange-600 transition-all shadow-md"
                >
                  <Icon name="heroicons:lock-closed" class="w-5 h-5" />
                  升级会员后访问
                </button>
                <!-- 普通访问按钮 -->
                <a
                  v-else
                  :href="tool.url"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium transition-colors"
                >
                  <Icon name="heroicons:arrow-top-right-on-square" class="w-5 h-5" />
                  访问官网
                </a>
                <button
                  @click="scrollToReviews"
                  class="px-6 py-3 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600"
                >
                  查看评论
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 工具截图轮播 -->
        <div v-if="tool.screenshots && tool.screenshots.length > 0" class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">产品截图</h2>
          <ScreenshotCarousel
            :screenshots="tool.screenshots"
            :tool-name="tool.name"
          />
        </div>
        <!-- 兼容旧的单张截图 -->
        <div v-else-if="tool.screenshot" class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">产品截图</h2>
          <img
            :src="tool.screenshot"
            :alt="`${tool.name} 截图`"
            class="w-full rounded-lg"
          />
        </div>

        <!-- 工具特性和详细信息 -->
        <div v-if="tool.features || tool.useCases || tool.pros || tool.cons || tool.recommendation" class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <ToolFeatures
            :features="tool.features"
            :use-cases="tool.useCases"
            :pros="tool.pros"
            :cons="tool.cons"
            :recommendation="tool.recommendation"
            :related-links="tool.relatedLinks"
            :docs-url="tool.docsUrl"
            :github-url="tool.githubUrl"
            :video-url="tool.videoUrl"
          />
        </div>

        <!-- 相关工具推荐 -->
        <div v-if="relatedTools && relatedTools.length > 0" class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <RelatedTools :tools="relatedTools" />
        </div>

        <!-- 评论区 -->
        <div id="reviews-section" class="space-y-6">
          <h2 class="text-2xl font-bold text-gray-900 dark:text-white">用户评价</h2>

          <!-- 发表评论表单 -->
          <div v-if="authStore.isAuthenticated && !hasReviewed">
            <ReviewForm
              :tool-id="tool.id"
              @submit="handleReviewSubmit"
            />
          </div>

          <div v-else-if="!authStore.isAuthenticated" class="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-6 text-center">
            <p class="text-gray-700 dark:text-gray-300 mb-4">
              登录后即可发表评论
            </p>
            <NuxtLink
              to="/login"
              class="inline-block px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              立即登录
            </NuxtLink>
          </div>

          <div v-else-if="hasReviewed" class="bg-gray-50 dark:bg-gray-800 rounded-lg p-6 text-center">
            <p class="text-gray-700 dark:text-gray-300">
              您已评论过该工具
            </p>
          </div>

          <!-- 评论列表 -->
          <ReviewsList
            :reviews="reviews"
            :stats="ratingStats"
            :loading="reviewsLoading"
            :total="reviewsTotal"
            :current-page="currentPage"
            :total-pages="totalPages"
            @edit="handleEditReview"
            @delete="handleDeleteReview"
            @mark-helpful="handleMarkHelpful"
            @change-page="handlePageChange"
            @filter-change="handleFilterChange"
          />
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else class="text-center py-12">
        <p class="text-gray-600 dark:text-gray-400 mb-4">工具不存在</p>
        <NuxtLink
          to="/tools"
          class="text-blue-600 dark:text-blue-400 hover:underline"
        >
          返回工具列表
        </NuxtLink>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '~/stores/auth'
import { useTools } from '~/composables/useTools'
import { useFavorites } from '~/composables/useFavorites'
import { useReviews } from '~/composables/useReviews'
import RatingStars from '~/components/RatingStars.vue'
import ReviewForm from '~/components/ReviewForm.vue'
import ReviewsList from '~/components/ReviewsList.vue'
import ScreenshotCarousel from '~/components/ScreenshotCarousel.vue'
import ToolFeatures from '~/components/ToolFeatures.vue'
import RelatedTools from '~/components/RelatedTools.vue'
import type { Tool, Review, RatingStats } from '~/types'

const route = useRoute()
const authStore = useAuthStore()
const toast = useToast()
const { getTool } = useTools()
const { checkFavorite, addFavorite, removeFavorite } = useFavorites()
const { 
  getReviews, 
  createReview, 
  deleteReview, 
  markReviewHelpful, 
  getToolRatingStats,
  checkUserReviewed 
} = useReviews()

const tool = ref<Tool | null>(null)
const loading = ref(true)
const isFavorited = ref(false)

const reviews = ref<Review[]>([])
const ratingStats = ref<RatingStats | undefined>(undefined)
const reviewsLoading = ref(false)
const reviewsTotal = ref(0)
const currentPage = ref(1)
const totalPages = ref(0)
const hasReviewed = ref(false)

// 新增：相关工具
const relatedTools = ref<Tool[]>([])

const formatNumber = (num: number | string): string => {
  const n = Number(num)
  if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M'
  if (n >= 1000) return (n / 1000).toFixed(1) + 'K'
  return n.toString()
}

const loadTool = async () => {
  try {
    loading.value = true
    const slug = route.params.slug as string
    tool.value = await getTool(slug)
    
    if (tool.value && authStore.isAuthenticated) {
      try {
        isFavorited.value = await checkFavorite(tool.value.id)
        hasReviewed.value = await checkUserReviewed(tool.value.id)
      } catch (error) {
        console.error('检查收藏/评论状态失败:', error)
        isFavorited.value = false
        hasReviewed.value = false
      }
    } else {
      // 未登录时重置状态
      isFavorited.value = false
      hasReviewed.value = false
    }
  } catch (error) {
    console.error('加载工具失败:', error)
  } finally {
    loading.value = false
  }
}

const loadReviews = async () => {
  if (!tool.value) return
  
  try {
    reviewsLoading.value = true
    const response = await getReviews({
      toolId: tool.value.id,
      page: currentPage.value,
      limit: 10,
      status: 'approved',
    })
    
    reviews.value = response.data
    reviewsTotal.value = response.meta.total
    totalPages.value = response.meta.totalPages
  } catch (error) {
    console.error('加载评论失败:', error)
  } finally {
    reviewsLoading.value = false
  }
}

const loadRatingStats = async () => {
  if (!tool.value) return
  
  try {
    ratingStats.value = await getToolRatingStats(tool.value.id)
  } catch (error) {
    console.error('加载评分统计失败:', error)
  }
}

const loadRelatedTools = async () => {
  if (!tool.value) return
  
  try {
    const { $api } = useNuxtApp()
    relatedTools.value = await $api(`/tools/${tool.value.id}/related?limit=6`)
  } catch (error) {
    console.error('加载相关工具失败:', error)
    relatedTools.value = []
  }
}

const toggleFavorite = async () => {
  if (!authStore.isAuthenticated) {
    toast.warning('请先登录')
    navigateTo('/login')
    return
  }
  
  if (!tool.value) return
  
  try {
    if (isFavorited.value) {
      await removeFavorite(tool.value.id)
      isFavorited.value = false
      toast.success('已取消收藏')
    } else {
      await addFavorite(tool.value.id)
      isFavorited.value = true
      toast.success('收藏成功')
    }
  } catch (error) {
    console.error('操作失败:', error)
    toast.error('操作失败，请重试')
  }
}

const showUpgradePrompt = () => {
  toast.warning('请先升级为会员')
  setTimeout(() => navigateTo('/pricing'), 500)
}

const handleReviewSubmit = async (data: any) => {
  try {
    await createReview(data)
    hasReviewed.value = true
    await loadReviews()
    await loadRatingStats()
    toast.success('评论提交成功')
  } catch (error: any) {
    toast.error(error?.data?.message || '提交评论失败')
  }
}

const handleEditReview = (review: Review) => {
  // TODO: 实现编辑评论功能
  console.log('编辑评论:', review)
}

const handleDeleteReview = async (id: number) => {
  if (!confirm('确定要删除这条评论吗？')) return
  
  try {
    await deleteReview(id)
    await loadReviews()
    await loadRatingStats()
    hasReviewed.value = false
    toast.success('评论已删除')
  } catch (error) {
    toast.error('删除评论失败')
  }
}

const handleMarkHelpful = async (id: number, helpful: boolean) => {
  if (!authStore.isAuthenticated) {
    toast.warning('请先登录')
    navigateTo('/login')
    return
  }
  
  try {
    await markReviewHelpful(id, helpful)
    await loadReviews()
    toast.success('感谢您的反馈')
  } catch (error: any) {
    console.error('操作失败:', error)
    if (error?.data?.message) {
      toast.warning(error.data.message)
    } else {
      toast.error('操作失败，请重试')
    }
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadReviews()
  scrollToReviews()
}

const handleFilterChange = (sortBy: string, filterRating: number) => {
  currentPage.value = 1
  loadReviews()
}

const scrollToReviews = () => {
  const element = document.getElementById('reviews-section')
  element?.scrollIntoView({ behavior: 'smooth' })
}

// 动态 SEO Meta 标签
const config = useRuntimeConfig()
const siteUrl = config.public.siteUrl || 'http://localhost:3000'

// 使用 SEO composable 生成结构化数据
const { generateToolSchema, generateBreadcrumbSchema } = useSEO()

useHead(() => {
  const title = tool.value 
    ? `${tool.value.name} - ${tool.value.description?.slice(0, 50) || '开发工具'} | DevToolsHub`
    : '工具详情 - DevToolsHub'
  
  const description = tool.value?.description || '优质的开发工具，提升你的开发效率。'
  const url = `${siteUrl}/tools/${route.params.slug}`
  
  // 生成结构化数据
  const scripts: any[] = []
  if (tool.value) {
    // 工具 Schema
    scripts.push({
      type: 'application/ld+json',
      innerHTML: JSON.stringify(generateToolSchema({
        name: tool.value.name,
        description: tool.value.description,
        url,
        logo: tool.value.logo,
        rating: typeof tool.value.rating === 'string' ? parseFloat(tool.value.rating) : tool.value.rating,
        reviewCount: tool.value.reviewCount,
        price: tool.value.isFree ? '免费' : tool.value.pricing,
        category: tool.value.category?.name
      })),
    })
    
    // 面包屑 Schema
    scripts.push({
      type: 'application/ld+json',
      innerHTML: JSON.stringify(generateBreadcrumbSchema([
        { name: '首页', url: siteUrl },
        { name: '工具', url: `${siteUrl}/tools` },
        { name: tool.value.name, url }
      ])),
    })
  }
  
  return {
    title,
    meta: [
      { name: 'description', content: description },
      { name: 'keywords', content: tool.value ? `${tool.value.name},开发工具,${tool.value.category?.name || ''}` : '开发工具' },
      
      // Open Graph
      { property: 'og:type', content: 'article' },
      { property: 'og:title', content: title },
      { property: 'og:description', content: description },
      { property: 'og:url', content: url },
      { property: 'og:image', content: tool.value?.logo || '' },
      
      // Twitter Card
      { name: 'twitter:card', content: 'summary_large_image' },
      { name: 'twitter:title', content: title },
      { name: 'twitter:description', content: description },
      { name: 'twitter:image', content: tool.value?.logo || '' },
      
      // 额外信息
      tool.value?.rating ? { name: 'rating', content: tool.value.rating.toString() } : null,
    ].filter(Boolean),
    link: [
      { rel: 'canonical', href: url },
    ],
    script: scripts,
  }
})

onMounted(async () => {
  await loadTool()
  if (tool.value) {
    await Promise.all([
      loadReviews(),
      loadRatingStats(),
      loadRelatedTools(),
    ])
  }
})
</script>

